package com.slipper.bpmn.parser;

import java.util.HashMap;
import java.util.Map;

import com.slipper.bpmn.model.Bpmn;
import com.slipper.bpmn.model.Common;
import com.slipper.bpmn.parser.support.*;
import org.dom4j.Element;

public class ParserFactory {
    private static final Map<String, IParser<?>> parserMap = new HashMap<>();
    private static final Map<String, String> typeMap = new HashMap<>();
    
    static {
        parserMap.put(Bpmn.START_NODE, new StartNodeParser());
        parserMap.put(Bpmn.TASK_NODE, new TaskNodeParser());
        parserMap.put(Bpmn.SCRIPT_NODE, new ScriptNodeParser());
        parserMap.put(Bpmn.BRANCH_NODE, new GatewayParser());
        parserMap.put(Bpmn.PARALLEL_NODE, new GatewayParser());
        parserMap.put(Bpmn.MERGE_NODE, new GatewayParser());
        parserMap.put(Bpmn.LINE_NODE, new LineParser());
        parserMap.put(Bpmn.END_NODE, new EndNodeParser());
        
        typeMap.put(Bpmn.START_NODE, "01");
        typeMap.put(Bpmn.TASK_NODE, "10");
        typeMap.put(Bpmn.SCRIPT_NODE, "15");
        typeMap.put(Bpmn.BRANCH_NODE, "20");
        typeMap.put(Bpmn.PARALLEL_NODE, "30");
        typeMap.put(Bpmn.MERGE_NODE, "31");
        typeMap.put(Bpmn.LINE_NODE, "40");
        typeMap.put(Bpmn.END_NODE, "99");
    }
    
    public static Object parser(Element element) {
        String type = element.getName();
        IParser<?> parser = parserMap.get(type);
        if (parser == null) {
            throw new RuntimeException("[" + type + "]解释器不存在！");
        }
        Common common = parser.parser(element);
        common.setType(typeMap.get(type));
        return common;
    }
}
